package com.mingliu.transactionalevent.service;

import com.mingliu.transactionalevent.model.InsAsset;
import com.mingliu.transactionalevent.repository.InsAssetRepository;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * 这个是编程式的方式
 */
@Service
public class InsAssetService2 {

    @Resource
    InsAssetRepository insAssetRepository;


    @Transactional(rollbackFor = Exception.class)
    public void assetCount() {
        Optional<InsAsset> byId = insAssetRepository.findById(171L);
        if(byId.isPresent()){
            insAssetRepository.getById(171L);
        }
        send(byId.get());
    }

    private void send(InsAsset insAsset) {
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {

                @Override
                public void beforeCommit(boolean readOnly) {
                    System.out.println(Thread.currentThread().getName() +"事务提交前执行");
                    TransactionSynchronization.super.beforeCommit(readOnly);
                }

                @Override
                public void beforeCompletion() {
                    System.out.println(Thread.currentThread().getName() +"事务完成前执行");
                    TransactionSynchronization.super.beforeCompletion();
                }

                @Override
                public void afterCommit() {
                    System.out.println(Thread.currentThread().getName() +"事务提交后执行");
                }

                @Override
                public void afterCompletion(int status) {
                    System.out.println(Thread.currentThread().getName() +"事务完成后执行");
                    TransactionSynchronization.super.afterCompletion(status);
                }
            });
        } else {
            System.out.println(Thread.currentThread().getName() +"没有启动事务");

        }
    }
}
